package com.wjn.basic.thread.threadpool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Queue;
import java.util.concurrent.*;

/**
 * 定时执行任务线程池
 */
public class ScheduledThreadPoolDemo {


    public static void main(String[] args) throws Exception {
        Queue<String> queue=new ConcurrentLinkedQueue<String>();
        //创建定时线程池
        ScheduledExecutorService executorscheduled = Executors.newScheduledThreadPool(3);
        for (int i=0;i<10;i++){
            queue.add("task"+i);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        //执行延迟任务
        for (int j=0;j<10;j++) {
            ScheduledFuture<String> scheduledFuture = executorscheduled.schedule(() -> {
                String value = queue.poll();
                if (value != null && value != "") {
                    System.out.println("时间:" + sdf.format(new Date()) + "线程" + Thread.currentThread().getName() + " 执行了task: " + value);
                }
                return "call";
            }, 3, TimeUnit.SECONDS);
            System.out.println(scheduledFuture.get());
        }

        executorscheduled.shutdown();
    }
}
